package serverlogic;

import java.sql.ResultSet;

import net.com.sunkey.protobuf.PluginRequest.PluginRequestData;
import net.com.sunkey.protobuf.PropertyData.Property;
import net.com.sunkey.protobuf.Protocol;
import net.com.sunkey.serverlogic.PluginData;
import net.com.sunkey.serverlogic.Plugin;
import net.com.sunkey.serverlogic.Server;
import net.com.sunkey.serverlogic.User;
import net.com.sunkey.serverlogic.Room;

/**
 * @author kohachiro
 *
 */
public class PluginBattle extends Plugin {
	/**
	 * 
	 */
	public PluginBattle() {
			
	}
	private boolean isPVE(Room room) {
		
		return false;
	}
	private boolean allInReady(Room room) {
		for (int i=0;i<6;i++){
			if (room.getScheduled().getProperty("seat"+i)!=null
					&&!room.getScheduled().getProperty("seat"+i).equals(room.getScheduled().getProperty("owner"))
					&&room.getScheduled().getProperty("ready"+i)==null){
				return false;
			}
		}
		return true;
	}	
	private int getSeat(Room room,String uid){
		for (int i=0;i<6;i++){
			String userId=room.getScheduled().getProperty("seat"+i);
			if (userId!=null&&userId.equals(uid)){
				return i;
			}
		}
		return -1;
	}
	private String getSeat(User user){
		for (int i=0;i<6;i++){
			String userId=user.getRoom().getScheduled().getProperty("seat"+i);
			if (userId!=null&&userId.equals(String.valueOf(user.getId()))){
				return String.valueOf(i);
			}
		}
		return null;
	}
	private String getSeat(String seatName){
		if (seatName.length()==5&&seatName.substring(0,4).equals("seat")){
			return seatName.substring(4,5);
		}
		return null;
	}
	public StringBuffer addMapProperty (StringBuffer stringBuffer,String key,String value){
		stringBuffer.append(key).append("=").append(value).append(",");
		return stringBuffer;
	}
	/**
	 * @param data
	 * @param user
	 * @return
	 * @throws Exception
	 */
	public PluginData getMapList(PluginRequestData data, User user) throws Exception{
		PluginData message=new PluginData(register(),data.getAction());
		StringBuffer sql = new StringBuffer("SELECT * FROM map");
		
		String type = data.getProperty(0).getValue();
		if ( type.equals("PVE") || type.equals("PVP") )
			sql.append(" Where type='").append(type).append("'");
		sql.append(" ORDER BY id");
		ResultSet rs = Server.getConnection().createStatement().executeQuery(sql.toString());
		while(rs.next()){
			StringBuffer value = new StringBuffer();
			value.append("id").append('\1').append(rs.getString("id")).append('\2');
			value.append("hp").append('\1').append(rs.getString("hp")).append('\2');
			value.append("name").append('\1').append(rs.getString("name")).append('\2');
			value.append("desc").append('\1').append(rs.getString("desc")).append('\2');
			value.append("type").append('\1').append(rs.getString("type")).append('\2');
			value.append("rank").append('\1').append(rs.getString("rank")).append('\2');
			value.append("wood").append('\1').append(rs.getString("wood")).append('\2');
			value.append("award").append('\1').append(rs.getString("award")).append('\2');
			value.append("stone").append('\1').append(rs.getString("stone")).append('\2');
			value.append("maxuser").append('\1').append(rs.getString("maxuser")).append('\2');
			value.append("monster").append('\1').append(rs.getString("monster")).append('\2');
			value.append("stagehp").append('\1').append(rs.getString("stagehp")).append('\2');
			value.append("minlevel").append('\1').append(rs.getString("minlevel")).append('\2');
			value.append("maxlevel").append('\1').append(rs.getString("maxlevel")).append('\2');
			value.append("winpoint").append('\1').append(rs.getString("winpoint")).append('\2');
			value.append("winfunction").append('\1').append(rs.getString("winfunction"));			
			message.addProperty(rs.getString("id"), value.toString());
		}		
		return message;
	}
	public PluginData setReady(PluginRequestData data, User user) throws Exception{
		PluginData message=new PluginData(register(),data.getAction());
		if (user.getRoom().getScheduled()==null){
			message.addProperty("result", Protocol.ReturnStatus.STATUS_FAILED_VALUE+"");
			return message;
		}
		Property property=data.getProperty(0);
		String seatId=getSeat(user);
		if (seatId==null){
			message.addProperty("result", Protocol.ReturnStatus.STATUS_FAILED_VALUE+"");
			return message;
		}
		if (property.getValue().equals("1")){
			String v=user.getRoom().getScheduled().getProperty("ready"+seatId);
			if (v==null){
				user.getRoom().getScheduled().addProperty("ready"+seatId,"1");
			}else if (!v.equals("1")){
				user.getRoom().getScheduled().removeProperty("ready"+seatId);	
				user.getRoom().getScheduled().addProperty("ready"+seatId,"1");
			}				
			message.addProperty("ready"+seatId,"1");
		}else{
			user.getRoom().getScheduled().removeProperty("ready"+seatId);
			message.addProperty("ready"+seatId,"0");
		}
		user.getRoom().pluginNotice(user.getId(),message);
		return message;
	}
	
	public PluginData startBattle(PluginRequestData data, User sender) throws Exception{
		PluginData message=new PluginData(register(),data.getAction());	
		if (sender.getRoom().getScheduled()==null){
			message.addProperty("result", Protocol.ReturnStatus.STATUS_FAILED_VALUE+"");
			return message;
		}
		
		Room room = sender.getRoom();
		String ownerid=room.getScheduled().getProperty("owner");
		int ownerSeatId=getSeat(room,ownerid);
		if ((room.getScheduled().getProperty("ready0")!=null
				||room.getScheduled().getProperty("ready1")!=null
				||room.getScheduled().getProperty("ready2")!=null
				||ownerSeatId >= 0 && ownerSeatId < 3 )
				&&(isPVE(room)
				||room.getScheduled().getProperty("ready3")!=null
				||room.getScheduled().getProperty("ready4")!=null
				||room.getScheduled().getProperty("ready5")!=null
				||ownerSeatId >= 3 && ownerSeatId < 6 )
				&&allInReady(sender.getRoom())
				){
			room.runScheduled();
			message.addProperty("result", Protocol.ReturnStatus.STATUS_OK_VALUE+"");
			return message;
		}
		message.addProperty("result", Protocol.ReturnStatus.STATUS_FAILED_VALUE+"");
		return message;
	}	
	public PluginData kickUser(PluginRequestData data, User user) throws Exception{
		PluginData message=new PluginData(register(),data.getAction());
		if (user.getRoom().getScheduled()==null){
			message.addProperty("result", Protocol.ReturnStatus.STATUS_FAILED_VALUE+"");
			return message;
		}
		
		Property property=data.getProperty(0);
		User nUser=User.get(Integer.parseInt(property.getValue()));
		if (nUser==null||!user.kickUser(nUser)){
			message.addProperty("result", Protocol.ReturnStatus.STATUS_FAILED_VALUE+"");
			return message;
		}		
		String seatId=getSeat(nUser);
		if (seatId==null){
			message.addProperty("result", Protocol.ReturnStatus.STATUS_FAILED_VALUE+"");
			return message;			
		}
		user.getRoom().getScheduled().removeProperty("seat"+seatId);
		user.getRoom().getScheduled().removeProperty("ready"+seatId);
		message.addProperty("seat"+seatId, "");
		message.addProperty("ready"+seatId, "0");
		message.addProperty("result", Protocol.ReturnStatus.STATUS_OK_VALUE+"");
		return message;		
	}
	public PluginData changeSeat(PluginRequestData data, User user) throws Exception{
		PluginData message=new PluginData(register(),data.getAction());
		if (user.getRoom().getScheduled()==null){
			message.addProperty("result", Protocol.ReturnStatus.STATUS_FAILED_VALUE+"");
			return message;
		}
		
		Property property=data.getProperty(0);
		String seatId=getSeat(user);
		if (property.hasName()&&property.getName().substring(0, 4).equals("seat")){
			String newSeatId=getSeat(property.getName());
			String value=user.getRoom().getScheduled().getProperty("seat"+newSeatId);
			if (value==null&&seatId!=null){
				//remove old seat
				user.getRoom().getScheduled().removeProperty("seat"+seatId);
				message.addProperty("seat"+seatId,"");
				if (user.getRoom().getScheduled().getProperty("ready"+seatId)!=null){
					user.getRoom().getScheduled().removeProperty("ready"+seatId);
					message.addProperty("ready"+seatId,"0");
				}
				//get new seat
				user.getRoom().getScheduled().addProperty("seat"+newSeatId,String.valueOf(user.getId()));
				message.addProperty("seat"+newSeatId, String.valueOf(user.getId()));
				if (user.getRoom().getScheduled().getProperty("ready"+newSeatId)!=null){
					user.getRoom().getScheduled().removeProperty("ready"+newSeatId);
					message.addProperty("ready"+newSeatId,"0");					
				}
				user.getRoom().pluginNotice(user.getId(),message);
				return message;
			}
		}
		message.addProperty("result", Protocol.ReturnStatus.STATUS_FAILED_VALUE+"");
		return message;
	}	
			
	/* (non-Javadoc)
	 * @see net.com.sunkey.serverlogic.Plugin#invoke(net.com.sunkey.protobuf.PluginRequest.PluginRequestData, net.com.sunkey.serverlogic.User)
	 */
	@Override
	public PluginData invoke(PluginRequestData data, User user)
			throws Exception {
		PluginData message=new PluginData(register(),data.getAction());
		message.addProperty("result", String.valueOf(Protocol.ReturnStatus.STATUS_PLUGIN_ACTION_NOT_FOUND_VALUE));
		return message;
	}

	/* (non-Javadoc)
	 * @see net.com.sunkey.serverlogic.Plugin#register()
	 */
	@Override
	public String register() {
		return "PluginBattle";
	}

}
